package extractor.view.database.connect;

import fx.FX;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import misc.Base;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by nuno-rafael-figueiredo on 23-03-2014.
 */
public class Login extends BorderPane {
    private final Base base = new Base(this);

    @FXML
    private TextField username;

    @FXML
    private PasswordField password;

    @FXML
    private Button signInButton;

    @FXML
    private Button cancelButton;

    private List<Listener> listeners = new ArrayList<>();

    public Login() {
        FX.load(this);
    }

    @FXML
    private void initialize(){
        signInButton.setOnAction(this::onSignIn);
        cancelButton.setOnAction(this::onCancel);
    }

    public Login setOnSignIn(Listener listener) {
        listeners.add(listener);
        return this;
    }

    private void onSignIn(ActionEvent actionEvent) {
        base.info("Signing in");
        for (Listener listener : listeners)
            new Thread(() -> listener.onSignIn(username.getText(), password.getText())).start();
        FX.close(this);
    }

    private void onCancel(ActionEvent actionEvent) {
        base.info("Canceled");
        FX.close(this);
    }

    public interface Listener {
        void onSignIn(String username, String password);
    }
}
